import java.awt.*; import java.applet.*; import java.awt.event.*; import javax.imageio.ImageIO; import java.io.File; import java.awt.image.BufferedImage; import java.io.IOException; public class RandomImageLocation extends Applet implements MouseListener { //===================================================================================================== // Data fields //===================================================================================================== public File f; public BufferedImage bi; public int imageX; //x coordinate of image - note that they are integers public int imageY; //y coordinate of image //===================================================================================================== // As always, the init method allows us to initialize our data fields. //===================================================================================================== public void init() { setBackground(Color.red); //--------------- //Importing image //--------------- try { String path = getCodeBase().toString().substring(6).replace("%20"," "); //WILL THIS WORK ON UNIX SERVERS? f = new File(path + "senators.jpg"); bi = ImageIO.read(f); } catch (IOException e) { //Blank } //--------------------------------- //Setting default image coordinates //--------------------------------- imageX = 100; imageY = 100; //-------- //Listener //-------- this.addMouseListener(this); } //===================================================================================================== // The paint method simply draws the image at the location specified by imageX and imageY. //===================================================================================================== public void paint(Graphics g) { Graphics2D g2D = (Graphics2D)g; g2D.drawImage(bi, imageX, imageY, this); //this method requires integer values for coordinates } //===================================================================================================== // When a mouse click occurs, we simply set that location as the image location and then repaint. //===================================================================================================== public void mouseClicked(MouseEvent e) { imageX = e.getX(); imageY = e.getY(); repaint(); } //===================================================================================================== // The following methods need to appear here because they are in the MouseListener interface. However, // we don't want to do anything when their related events occur. Therefore, we leave them blank. //===================================================================================================== public void mouseEntered(MouseEvent e) {} public void mouseExited (MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} }